package com.dhy.command;

import com.dhy.builder.CommandBuilder;
import com.dhy.builder.StandardCommandBuilder;
import com.dhy.config.ClientConfig;
import com.dhy.parse.CommandParse;
import com.dhy.parse.StandardCommandParse;
import com.dhy.socket.RedisClientSocket;

import java.io.IOException;

import static com.dhy.constants.CommandConstants.SEPARATOR;

/**
 * @author 大忽悠
 * @create 2022/5/29 20:29
 */
public abstract class AbstractCommand implements Command{
    protected CommandBuilder commandBuilder=new StandardCommandBuilder();
    protected RedisClientSocket redisClientSocket=new RedisClientSocket();

    @Override
    public Object execute(String args) {
        try {
            return execute(args.split(SEPARATOR));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public Object execute(String... args) throws IOException {
        //1.拼接命令字符串
        String command = commandBuilder.buildCommand(args);
        return doExecute(command);
    }

    /**
     * 真正执行命令
     */
    public abstract Object doExecute(String commandString) throws IOException;

    public void setCommandBuilder(CommandBuilder commandBuilder) {
        this.commandBuilder = commandBuilder;
    }

    public void setRedisClientSocket(RedisClientSocket redisClientSocket) {
        this.redisClientSocket = redisClientSocket;
    }

    public Object authIfRequired(ClientConfig config){
        if(!config.getNEED_AUTH()){
            return "免密登录中";
        }
        StringBuilder builder=new StringBuilder();
        builder.append("auth ").append(config.getPassword());
        return execute(builder.toString());
    }
}
